package com.dk.bleNfc.DeviceManager;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

public class BluetoothHelper {

    public interface BluetoothListener {
        void onBluetoothReady();                     // 蓝牙已就绪（适配器可用）
        void onDeviceFound(BluetoothDevice device);  // 扫描到一个设备（可用来展示列表）
        void onDeviceConnected();                    // 连接成功
        void onDeviceDisconnected();                 // 连接断开
        void onDataReceived(byte[] data);            // 收到来自蓝牙设备的数据（如按键）
        void onError(String message);                // 发生错误
    }

    // 蓝牙串口服务的 UUID（SPP）
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    private final BluetoothAdapter bluetoothAdapter;
    private BluetoothDevice targetDevice;
    private BluetoothSocket bluetoothSocket;
    private InputStream inputStream;
    private ConnectThread connectThread;
    private ReadThread readThread;

    private final CopyOnWriteArrayList<BluetoothListener> listeners = new CopyOnWriteArrayList<>();
    private final WeakReference<Context> contextRef;
    private boolean isScanning = false;

    public BluetoothHelper(Context context) {
        this.contextRef = new WeakReference<>(context);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        checkBluetoothSupport();
    }

    private void checkBluetoothSupport() {
        if (bluetoothAdapter == null) {
            notifyError("该设备不支持蓝牙");
        } else {
            notifyBluetoothReady();
        }
    }

    // ========== 扫描相关 ==========

    public void startScan() {
        if (isScanning) return;
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            notifyError("蓝牙未开启");
            return;
        }

        isScanning = true;
        Context context = contextRef.get();
        if (context == null) return;

        // 注册广播，用于接收扫描到的设备
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        context.registerReceiver(scanReceiver, filter);

        boolean started = bluetoothAdapter.startDiscovery();
        Log.d("BluetoothHelper", "开始扫描: " + started);
    }

    public void stopScan() {
        if (!isScanning) return;

        isScanning = false;
        bluetoothAdapter.cancelDiscovery();

        Context context = contextRef.get();
        if (context != null) {
            try {
                context.unregisterReceiver(scanReceiver);
            } catch (IllegalArgumentException ignored) {
            }
        }
    }

    private final BroadcastReceiver scanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    String name = device.getName();
                    String address = device.getAddress();
                    Log.d("BluetoothHelper", "发现设备: " + name + " (" + address + ")");
                    // 通知外部监听器，你可以在这里匹配你的设备
                    for (BluetoothListener listener : listeners) {
                        listener.onDeviceFound(device);
                    }
                    // 示例：自动连接某个设备（你也可以自己决定何时连接）
                    // 比如根据设备名或 MAC 地址
                    if ("Bluetooth remote".equals(name)) {
                        stopScan();
                        connectToDevice(device);
                    } else if (address != null && address.equalsIgnoreCase("XX:XX:XX:XX:XX:XX")) {
                        stopScan();
                        connectToDevice(device);
                    }
                }
            }
        }
    };

    // ========== 连接相关 ==========

    // 方式1：通过 BluetoothDevice 对象连接（比如你已通过扫描或其他方式获得）
    public void connectToDevice(BluetoothDevice device) {
        if (device == null) {
            notifyError("设备为空");
            return;
        }
        this.targetDevice = device;
        startConnectThread();
    }

    // 方式2：通过 MAC 地址连接（需蓝牙已开启）
    public void connectByMac(String macAddress) {
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            notifyError("请先开启蓝牙");
            return;
        }
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAddress);
        connectToDevice(device);
    }

    private void startConnectThread() {
        stopAllThreads(); // 先停止之前的连接和读取

        connectThread = new ConnectThread(targetDevice);
        connectThread.start();
    }

    private class ConnectThread extends Thread {
        private final BluetoothDevice device;
        private BluetoothSocket tmpSocket;

        ConnectThread(BluetoothDevice device) {
            this.device = device;
            try {
                tmpSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                notifyError("创建Socket失败: " + e.getMessage());
            }
        }

        @Override
        public void run() {
            try {
                if (tmpSocket != null) {
                    tmpSocket.connect(); // 阻塞式连接
                    bluetoothSocket = tmpSocket;
                    tmpSocket = null;

                    // 连接成功，获取输入流
                    inputStream = bluetoothSocket.getInputStream();

                    notifyConnected();

                    // 启动读取线程
                    readThread = new ReadThread(inputStream);
                    readThread.start();
                }
            } catch (IOException e) {
                notifyError("连接失败: " + e.getMessage());
                closeSocketQuietly(tmpSocket);
                closeSocketQuietly(bluetoothSocket);
            }
        }
    }

    // ========== 数据读取线程 ==========

    private class ReadThread extends Thread {
        private final InputStream mmInStream;

        ReadThread(InputStream inputStream) {
            this.mmInStream = inputStream;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;

            while (!isInterrupted() && mmInStream != null) {
                try {
                    bytes = mmInStream.read(buffer);
                    if (bytes > 0) {
                        byte[] received = new byte[bytes];
                        System.arraycopy(buffer, 0, received, 0, bytes);
                        notifyDataReceived(received);
                    }
                } catch (IOException e) {
                    notifyError("读取数据出错，可能已断开: " + e.getMessage());
                    break;
                }
            }
        }
    }

    // ========== 断开与清理 ==========

    public void disconnect() {
        stopAllThreads();
        closeSocketQuietly(bluetoothSocket);
        notifyDisconnected();
    }

    private void stopAllThreads() {
        if (connectThread != null) {
            connectThread.interrupt();
            connectThread = null;
        }
        if (readThread != null) {
            readThread.interrupt();
            readThread = null;
        }
    }

    private void closeSocketQuietly(BluetoothSocket socket) {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    // ========== Listener 管理 ==========

    public void addListener(BluetoothListener listener) {
        if (listener != null && !listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    public void removeListener(BluetoothListener listener) {
        listeners.remove(listener);
    }

    private void notifyBluetoothReady() {
        for (BluetoothListener listener : listeners) {
            if (listener != null) {
                new Handler(Looper.getMainLooper()).post(listener::onBluetoothReady);
            }
        }
    }

    private void notifyDeviceFound(BluetoothDevice device) {
        for (BluetoothListener listener : listeners) {
            if (listener != null) {
                new Handler(Looper.getMainLooper()).post(() -> listener.onDeviceFound(device));
            }
        }
    }

    private void notifyConnected() {
        for (BluetoothListener listener : listeners) {
            if (listener != null) {
                new Handler(Looper.getMainLooper()).post(listener::onDeviceConnected);
            }
        }
    }

    private void notifyDisconnected() {
        for (BluetoothListener listener : listeners) {
            if (listener != null) {
                new Handler(Looper.getMainLooper()).post(listener::onDeviceDisconnected);
            }
        }
    }

    private void notifyDataReceived(byte[] data) {
        for (BluetoothListener listener : listeners) {
            if (listener != null) {
                new Handler(Looper.getMainLooper()).post(() -> listener.onDataReceived(data));
            }
        }
    }

    private void notifyError(String message) {
        for (BluetoothListener listener : listeners) {
            if (listener != null) {
                new Handler(Looper.getMainLooper()).post(() -> listener.onError(message));
            }
        }
    }
}
